import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '@/views/login'
// import Register from '@/views/register'
// import Detail from '@/views/detail'
import Layout from '@/views/layout'

// import Like from '@/views/like'
// import Article from '@/views/article'
// import Collect from '@/views/collect'
// import User from '@/views/user'

import { getToken } from '@/utils/storage'

const Login = () => import('@/views/login')
const Register = () => import('@/views/register')
const Detail = () => import('@/views/detail')
const Like = () => import('@/views/like')
const Article = () => import('@/views/article')
const Collect = () => import('@/views/collect')
const User = () => import('@/views/user')
Vue.use(VueRouter)

// const routes = [

// ]

const router = new VueRouter({
  routes: [
    {
      path: '/login',
      component: Login
    },
    {
      path: '/register',
      component: Register
    },
    {
      path: '/detail/:id',
      component: Detail
    },
    {
      path: '/',
      component: Layout,
      redirect: '/article', // 如果匹配到的路径是/ 就会重定向到article页面
      children: [
        {
          path: '/article',
          component: Article
        },
        {
          path: '/like',
          component: Like
        },
        {
          path: '/collect',
          component: Collect
        },
        {
          path: '/user',
          component: User
        }
      ]
    }
  ]
})

const whiteList = ['/login', '/register'] // 白名单列表，记录无需权限访问的所有页面

router.beforeEach((to, from, next) => {
  const token = getToken()
  // 如果有token，直接放行
  if (token) {
    next()
  } else {
    // 没有token的人, 看看你要去哪
    // (1) 访问的是无需授权的页面（白名单），也是放行
    //     就是判断，访问的地址，是否在白名单数组中存在 includes
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // (2) 否则拦截到登录
      next('/login')
    }
  }
})
export default router
